package cn.dankal.flyaudio.personal.setting;

import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.HandlerThread;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import api.UserServiceFactory;
import butterknife.BindView;
import butterknife.OnClick;
import cn.codeguy.component_download.DownloadCallback;
import cn.codeguy.component_download.DownloadHelper;
import cn.codeguy.component_download.InstallApk;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.protocol.PersonalProtocol;
import cn.dankal.basiclib.rx.AbstractDialogSubscriber;
import cn.dankal.basiclib.util.StringUtil;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.widget.CommonDialog;
import cn.dankal.basiclib.widget.titlebar.SingleTextTitle;
import cn.dankal.business.pojo.VersionBean;
import cn.dankal.flyaudio.R;
import me.jessyan.progressmanager.ProgressListener;
import me.jessyan.progressmanager.ProgressManager;
import me.jessyan.progressmanager.body.ProgressInfo;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * description: 当前版本
 *
 * @author vane
 * @since 2018/8/20
 */
@Route(path = PersonalProtocol.APP_VERSION)
public class AppVersionActivity extends BaseActivity {
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_new_version)
    TextView tvNewVersion;
    @BindView(R.id.bt_check)
    Button btnCheck;

    private boolean isNewVersion = false;//是否发现新版本

    @Override
    protected int getLayoutId() {
        return R.layout.activity_app_version;
    }

    @Override
    protected void initComponents() {
        addTitleBar(new SingleTextTitle("检查更新"));

        String versionName = "内测版";
        try {
            versionName = this.getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        tvVersion.setText("当前版本 " + versionName);

        UserServiceFactory.getAppVersion()
                .subscribe(new AbstractDialogSubscriber<VersionBean>(this) {
                    @Override
                    public void onNext(VersionBean appVersion) {
                        if (appVersion != null) {
                            int version_code = Integer.valueOf(StringUtil.safeString(appVersion.appVersion, "0"));
                            boolean force = appVersion.appForce.equals("1");
                            int currentVersionCode = getVersionCode();
                            if (force || (version_code > currentVersionCode && currentVersionCode != -1)) {
                                tvNewVersion.setText("发现新版本" + appVersion.versionName);
                                isNewVersion = true;
                            } else {
                                tvNewVersion.setText("暂未发现新版本");
                                isNewVersion = false;
                                btnCheck.setText("检查更新");
                            }
                        }
                    }
                });

    }

    @OnClick(R.id.bt_check)
    public void check(View view) {
        checkVersion();
    }

    public void checkVersion() {

        UserServiceFactory.getAppVersion()
                .subscribe(new AbstractDialogSubscriber<VersionBean>(this) {
                    @Override
                    public void onNext(VersionBean appVersion) {
                        if (appVersion != null) {
                            int version_code = Integer.valueOf(StringUtil.safeString(appVersion.appVersion, "0"));
                            boolean force = appVersion.appForce.equals("1");

                            int currentVersionCode = getVersionCode();
                            if (force || (version_code > currentVersionCode && currentVersionCode != -1)) {
                                if (isNewVersion) {
                                    showVersionDialog("是否下载新版本", appVersion.appDownloadUrl, force, appVersion.upgradePrompt);
                                } else {
                                    showVersionDialog("发现新版本", appVersion.appDownloadUrl, force, appVersion.upgradePrompt);
                                }
                            } else {
                                ToastUtils.showShort("已是最新版本");
                            }
                        }
                    }
                });
    }

    public int getVersionCode() {
        try {
            int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
            return versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }


    private CommonDialog commonDialog;
    private CommonDialog.Builder builder;
    private Call<ResponseBody> downloadCall = null;

    private void downloadApk(String appDownloadUrl, boolean force) {
        AndPermission.with(AppVersionActivity.this)
                .runtime()
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(data -> {
                    ProgressManager.getInstance().addResponseListener(appDownloadUrl, new ProgressListener() {
                        @Override
                        public void onProgress(ProgressInfo progressInfo) {
                            if (loadingDialog != null) {
                                loadingDialog.setContent("下载中...(" + progressInfo.getPercent() + "%)");
                            }
                        }

                        @Override
                        public void onError(long id, Exception e) {

                        }
                    });

                    DownloadHelper.download(appDownloadUrl, "app.apk", "app", new DownloadCallback() {
                        @Override
                        public void onInitComplete(Call<ResponseBody> download) {
                            downloadCall = download;
                        }

                        @Override
                        public void onStart() {
                            showLoadingDialog();
                            loadingDialog.setCancelable(!force);
                            loadingDialog.setContent("准备下载");
                            loadingDialog.setOnDismissListener(dialog -> {
                                if (downloadCall != null) {
                                    downloadCall.cancel();
                                }
                            });
                        }

                        @Override
                        public void onUpdate(String value) {

                        }

                        @Override
                        public void onDownloadComplete(String msg, String path) {
                            runOnUiThread(() -> {
                                loadingDialog.dismiss();
                                loadingDialog.setCancelable(true);
                                InstallApk.startInstall(AppVersionActivity.this, path);
                            });
                        }

                        @Override
                        public void onDownloadError(String msg) {
                            runOnUiThread(() -> {
                                loadingDialog.setContent(msg);
                                loadingDialog.dismiss();
                            });
                        }
                    });
                }).onDenied(data -> ToastUtils.showShort("请到设置打开读写权限")).start();
    }

    public void showVersionDialog(String title, String url, boolean force, String upgradePrompt) {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(data -> {

                    builder = new CommonDialog.Builder(this).setTitle(title)
                            .setSubtitle(upgradePrompt)
                            .setPositiveButton("下载", Color.parseColor("#D70D18"), type -> {
                                downloadApk(url, force);
                            });

                    if (!force) {
                        builder.setNegativeButton("取消", Color.BLACK, type -> builder.getDialog().dismiss());
                    } else {
                        builder.setmCancelable(false);
                    }

                    commonDialog = builder.create();

                    commonDialog.show();

                }).onDenied(data -> ToastUtils.showShort("请到设置打开读写权限")).start();
    }
}
